package com.st.mall.scart.controller;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.st.mall.product.model.ProductModel;
import com.st.mall.product.service.IProductService;
import com.st.mall.scart.model.ScartModel;
import com.st.mall.scart.service.IScartService;
import com.st.mall.user.model.UserModel;

@Controller
@RequestMapping("/scart")
public class ScartController {

	@Autowired
	private IScartService service;
	
	@Autowired
	private IProductService proService;
	
	@RequestMapping("/add")
	@ResponseBody
	public int insert(ScartModel scartModel,HttpSession session) {
		Object obj = session.getAttribute("user");
		UserModel user = (UserModel)obj;
		System.out.println(user.getCode());
		System.out.println(scartModel);
		if(obj==null)
			return 0;
		ScartModel model = service.selectOne(scartModel);
		if(model != null) {
			int sum = model.getNumb();
			scartModel.setNumb(sum+scartModel.getNumb());
			return service.update(scartModel);
		}else {
			scartModel.setNumb(1);
			scartModel.setCustCode(user.getCode());
			return service.insert(scartModel);
		}
	}
	
	@RequestMapping("/del")
	@ResponseBody
	public int delete(String proCode) {	
		return service.delete(proCode);
	}
	
	@RequestMapping(value = "/selectAll",produces = "application/json;charset=utf-8")
	@ResponseBody
	public String selectAll(HttpSession session) {
		UserModel user = (UserModel) session.getAttribute("user");
		if(user==null)
			return "0";
		ScartModel scartModel = new ScartModel();
		scartModel.setCustCode(user.getCode());
		List<ScartModel> list = service.selectAll(scartModel);
		return new JSONArray(list).toString();	
	}
	
	/**
	 * 数量改变影响价格
	 * @param cartModel
	 * @return
	 */
	@RequestMapping(value = "/change", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
	@ResponseBody
	public int num(ScartModel scartModel, HttpSession session) {
		UserModel user = (UserModel) session.getAttribute("user");
		ProductModel prodcut = proService.selectId(scartModel.getProCode());
		Double total = scartModel.getNumb()*prodcut.getPrice();
		scartModel.setTotal(total);
		scartModel.setCustCode(user.getCode());
		return service.update(scartModel);
	}
	
}
